package com.fjzx.androidframe.base.util;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author xiongyongcong
 */
public class XJsonUtil {
    private static Moshi moshi = new Moshi.Builder().build();

    public static <T> T toObject(String jsonStr, Class<T> clazz) {
        checkNonNull();
        JsonAdapter<T> adapter = moshi.adapter(clazz);
        try {
            return adapter.fromJson(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> toObjectList(String jsonStr, Class<T> clazz) {
        checkNonNull();
        Type listType = Types.newParameterizedType(List.class, clazz);
        JsonAdapter<List<T>> adapter = moshi.adapter(listType);
        try {
            return adapter.fromJson(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJson(Object object) {
        checkNonNull();
        JsonAdapter adapter = moshi.adapter(object.getClass());
        return adapter.toJson(object);
    }

    private static void checkNonNull() {
        if (moshi == null) {
            moshi = new Moshi.Builder().build();
        }
    }
}
